#!/bin/bash

echo "🔧 开始修复部署问题..."

# 1. 停止现有容器
echo "🛑 停止现有容器..."
docker compose down

# 2. 检查并生成 SSL 证书
echo "🔐 检查 SSL 证书..."
if [ ! -d "ssl" ] || [ ! -f "ssl/nginx.crt" ] || [ ! -f "ssl/nginx.key" ]; then
    echo "生成 SSL 证书..."
    chmod +x generate-ssl.sh
    ./generate-ssl.sh
else
    echo "SSL 证书已存在"
fi

# 3. 检查 web 目录
echo "📁 检查 web 目录..."
if [ ! -d "web" ]; then
    echo "❌ web 目录不存在，请先运行 npm run build"
    exit 1
fi

# 4. 重新启动容器
echo "🚀 重新启动容器..."
docker compose up -d

# 5. 等待容器启动
echo "⏳ 等待容器启动..."
sleep 5

# 6. 检查容器状态
echo "📊 检查容器状态..."
docker compose ps

# 7. 检查容器日志
echo "📋 容器日志："
docker compose logs --tail=10

# 8. 测试连接
echo "🌐 测试连接..."
echo "测试 HTTP (容器内端口 80)："
docker exec cyjw-web curl -I http://localhost:80 2>/dev/null || echo "❌ HTTP 连接失败"

echo ""
echo "测试 HTTPS (容器内端口 443)："
docker exec cyjw-web curl -I https://localhost:443 2>/dev/null || echo "❌ HTTPS 连接失败"

echo ""
echo "✅ 修复完成！"
echo ""
echo "🌐 访问地址："
echo "   HTTP:  http://localhost:8880"
echo "   HTTPS: https://localhost:8443"
echo ""
echo "🔍 如果仍有问题，请运行 ./debug.sh 进行详细诊断" 